package com.animal.controller;


import com.animal.auto.JSONAuthentication;
import com.animal.entity.AnMeans;
import com.animal.entity.AnUser;
import com.animal.mapper.AnMeansMapper;
import com.animal.mapper.AnUserMapper;
import com.animal.response.Result;
import com.animal.service.AnUserService;
import com.animal.utils.UpPhotoNameUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.security.util.Password;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.WriteAbortedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author animal
 * @since 2022-01-28
 */
@RestController
@RequestMapping("/an-user")
public class AnUserController extends JSONAuthentication {
    @Autowired
    private AnUserMapper anUserMapper;
    public static final QueryWrapper WRAPPER = new QueryWrapper();
    @Autowired
    AnUserService anUserService;
    @Autowired
    AnMeansMapper anMeansMapper;


    @ApiOperation(value = "添加用户")
    @PostMapping("/add")
    public void addUser(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response, @RequestParam("username") String username, @RequestParam("password") String password1,@RequestParam("level") int level,@RequestParam("role") String role) throws  Exception{
        AnUser anUser=new AnUser();
        anUser.setUsername(username);
        anUser.setPassword(password1);
        anUser.setRole(role);
        anUser.setLevel(level);
        AnUser a= anUserMapper.findByname(anUser.getUsername());
        if(a!=null){
            Result result=Result.error();
            result.setMessage("该用户已存在");
            this.WriteJSON(request, response, result);
        }else {
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            String fileName = UpPhotoNameUtils.getPhotoName("img",imageFileName);
            Path path = Paths.get("D:\\自己的项目\\流浪动物救助\\adopt\\adopt\\src\\assets\\picture\\" + fileName);
            //“C:\\框架\\D4\\d4_pc_ui\\src\\assets\\images\\img\\”为本地目录
            Files.write(path, bytes);//写入文件
            String avatar_url=fileName;
            anUser.setHeadPicture(avatar_url);
            response.reset();
            Date date = new Date();
            Timestamp timestamp = new Timestamp(date.getTime());
            anUser.setUsCreatTime(timestamp);
            String password= new BCryptPasswordEncoder().encode(anUser.getPassword());
            anUser.setPassword(password);
            System.out.println(password);
            int i=anUserMapper.insert(anUser);
            if(i>0){
                Result ok = Result.ok();
                this.WriteJSON(request, response, ok);
            } else {
                Result error = Result.error();
                this.WriteJSON(request, response, error);
            }
        }

    }

    @ApiOperation(value = "删除用户")
    @PostMapping("/del")
    public void delUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("userId") int userId ) throws Exception{
        int i=anUserMapper.deleteById(userId);
        if(i>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "修改用户")
    @PostMapping("/upd")
    public void updUser(HttpServletRequest request, HttpServletResponse response, @RequestBody AnUser anUser)throws Exception{
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        anUser.setUsUpdTime(timestamp);
        String password= new BCryptPasswordEncoder().encode(anUser.getPassword());
        anUser.setPassword(password);
        int i=anUserMapper.updateById(anUser);
        if(i>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查询用户")
    @PostMapping("/look")
    public void lookUser(HttpServletRequest request, HttpServletResponse response,@RequestParam("size") int size,@RequestParam("current") int current)throws  Exception{


        List<AnUser> userPages= anUserService.lookAll(size,current);

        Result ok = Result.ok().data("user",userPages);

        this.WriteJSON(request, response, ok);
    }

    @ApiOperation(value = "修改用户头像")
    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                   HttpServletRequest request,HttpServletResponse response,@RequestParam("userId") int userId) throws  Exception{

        try {
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            String fileName = UpPhotoNameUtils.getPhotoName("img",imageFileName);
            Path path = Paths.get("D:\\自己的项目\\流浪动物救助\\adopt\\adopt\\src\\assets\\picture\\" + fileName);
            //“C:\\框架\\D4\\d4_pc_ui\\src\\assets\\images\\img\\”为本地目录
            Files.write(path, bytes);//写入文件
            String avatar_url=fileName;
            AnUser anUser =new AnUser();
            anUser.setUserId(userId);
            anUser.setHeadPicture(avatar_url);
             int n= anUserMapper.updateById(anUser);
            response.reset();
             if(n>0){
                 Result result=Result.ok();
                 this.WriteJSON(request, response, result);

             }else{
                 Result result=Result.error();
                 this.WriteJSON(request, response, result);

             }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";

    }

    @ApiOperation(value = "通过名字查找用户")
    @PostMapping("/findByname")
    public void findByname(HttpServletRequest request, HttpServletResponse response,@RequestParam("username") String username)throws  Exception{
        WRAPPER.like("username",username);
        List<AnUser> list =anUserMapper.selectList(WRAPPER);
        QueryWrapper wrapper=new QueryWrapper();
        for(AnUser a:list){

            wrapper.eq("user_id",a.getUserId());
            a.setAnMeans(anMeansMapper.selectOne(wrapper));
        }
        if(list.size()>0){
            Result ok = Result.ok().data("user",list);
            this.WriteJSON(request, response, ok);
        }
        Result error = Result.error();
        error.setMessage("没有此用户");
        this.WriteJSON(request, response, error);
    }
    @ApiOperation(value = "修改密码")
    @PostMapping("/updpassword")
    public void updpassword(HttpServletRequest request, HttpServletResponse response,@RequestBody AnUser anUser)throws  Exception{
      AnUser anUser1=anUserMapper.selectById(anUser.getUserId());
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        String password= new BCryptPasswordEncoder().encode(anUser.getRpassword());
      if(encoder.matches(anUser.getPassword(),anUser1.getPassword())){
        anUser.setPassword(password);

        int i=anUserMapper.updateById(anUser);
        if(i>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        }else{
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }

      }else{
          Result error = Result.error();
          error.setMessage("密码不正确");
          this.WriteJSON(request, response, error);
      }
    }
    @ApiOperation(value = "通过用户id查找用户")
    @PostMapping("/findById")
    public void findById(HttpServletRequest request, HttpServletResponse response,@RequestParam("userId") int userId)throws  Exception{

        AnUser list =anUserMapper.selectById(userId);
        if(list!=null){
            Result ok = Result.ok().data("user",list);
            this.WriteJSON(request, response, ok);
        }
        Result error = Result.error();
        error.setMessage("没有此用户");
        this.WriteJSON(request, response, error);
    }
    @ApiOperation(value = "通过用户id进行充值")
    @PostMapping("/deposit")
    public void deposit(HttpServletRequest request, HttpServletResponse response,@RequestParam("userId") int userId,@RequestParam("balance") float balance)throws  Exception{

        AnUser list =anUserMapper.selectById(userId);
        float balance1=list.getBalance();
        float balance2=balance1+balance;
        list.setBalance(balance2);
        if( anUserMapper.updateById(list)>0){
            Result ok = Result.ok().message("充值成功");
            this.WriteJSON(request, response, ok);
        }
        Result error = Result.error();
        error.setMessage("充值失败");
        this.WriteJSON(request, response, error);
    }
}

